<?php

namespace App\Http\Controllers;

use App\Http\Requests\SystemConfigStoreRequest;
use App\Models\SystemConfig;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SystemConfigController extends Controller
{
    /**
     * 系统配置列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): \Illuminate\Http\JsonResponse
    {
        $systemConfig = new SystemConfig();
        $systemConfig  = $systemConfig->index($request);
        return response()->json(['data' => $systemConfig]);
    }

    /**
     * 新增系统配置
     * @param SystemConfigStoreRequest $request
     * @return JsonResponse
     */
    public function store(SystemConfigStoreRequest $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->only(['name', 'type', 'key', 'value', 'description']);
        SystemConfig::create($data);
        return response()->json(['message' => '新增系统配置成功']);
    }

    /**
     * 查看系统配置详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id): \Illuminate\Http\JsonResponse
    {
        $systemConfig = SystemConfig::find($id);
        return response()->json(['data' => $systemConfig]);
    }


    /**
     * 更新系统配置
     * @param SystemConfigStoreRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(SystemConfigStoreRequest $request, $id): \Illuminate\Http\JsonResponse
    {
        $systemConfig = SystemConfig::find($id);
        if (!$systemConfig) {
            return response()->json(['message' => '系统配置不存在'], 404);
        }
        if ($systemConfig->type == 1 && $request->input('type') != 1) {
            return response()->json(['message' => '系统配置不能修改配置类型'], 403);
        }
        $systemConfig->update($request->only(['name', 'type', 'key', 'value', 'description']));
        return response()->json(['message' => '更新系统配置成功']);
    }

    /**
     * 删除系统配置
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id): \Illuminate\Http\JsonResponse
    {
        $systemConfig = SystemConfig::find($id);
        if (!$systemConfig) {
            return response()->json(['message' => '系统配置不存在'], 404);
        }
        if ($systemConfig->type == 'system') {
            return response()->json(['message' => '系统配置不能删除'], 403);
        }
        return response()->json(['message' => '删除系统配置成功']);
    }

}
